package org.example.thread5;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子操作 - 保证数据安全
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/10/31 17:19
 */
public class MyThread5 extends Thread {
    // 如果是普通的 private static int count; cout--;则很容易导致线程之间数据读取混乱
    private static AtomicInteger atomicInteger = new AtomicInteger(9);

    @Override
    public void run() {
        try {
            for (int i = 0; i < 3; i++) {
                atomicInteger.getAndDecrement();
                System.out.println(currentThread().getName() + "\ti=" + (i) + "\t atomicInteger=" + atomicInteger.get());
                Thread.sleep(500 + new Random().nextInt(1000));//稍作延迟，如果完全执行的太快，线程之间仍然会出现脏读的
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService;
        executorService = Executors.newCachedThreadPool();
        //使用线程池新开3个线程任务去对 MyThread 类中的atomicInteger做自减操作
        for (int i = 0; i < 3; i++) {
            executorService.execute(new MyThread5());
        }
    }
    //pool-1-thread-1	i=0	 atomicInteger=8
    //pool-1-thread-2	i=0	 atomicInteger=7
    //pool-1-thread-3	i=0	 atomicInteger=6
    //pool-1-thread-1	i=1	 atomicInteger=5
    //pool-1-thread-2	i=1	 atomicInteger=4
    //pool-1-thread-3	i=1	 atomicInteger=3
    //pool-1-thread-1	i=2	 atomicInteger=2
    //pool-1-thread-2	i=2	 atomicInteger=1
    //pool-1-thread-3	i=2	 atomicInteger=0
}